/**
 *  Eclipse Public License 1.0
 */
package org.fireblade.easysms;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.PowerManager;
import android.util.Log;
import backport.android.bluetooth.BluetoothServerSocket;
import backport.android.bluetooth.BluetoothSocket;

/**
 * Bluetooth service. Gets started by the acl device connected intent. first start, the socket is
 * created but client will not use it. client will use it on second connect.
 */
public class BluetoothService extends AbstractService {
  /**
   * own log tag
   */
  protected static final String LOGTAG = MainActivity.EASY_SMS + BluetoothService.class.getSimpleName();
  /**
   * the thread for handling the IO
   */
  static Thread serverThread = null;

  /**
   * the server socket
   */
  static BluetoothServerSocket btServerSocket = null;
  /**
   * cpu wake lock
   */
  static PowerManager.WakeLock wakeLock;


  @Override
  public void onCreate() {
    super.onCreate();
    Log.d(LOGTAG, "onCreate");
  }


  /*
   * (non-Javadoc)
   * @see org.fireblade.easysms.AbstractService#getNotificationId()
   */
  @Override
  protected int getNotificationId() {
    return 2;
  }


  /*
   * (non-Javadoc)
   * @see org.fireblade.easysms.AbstractService#getConnectionType()
   */
  @Override
  protected String getConnectionType() {
    return "Bluetooth";
  }


  @Override
  public void onStart(Intent intent, int startId) {
    super.onStart(intent, startId);

    Log.d(LOGTAG, "onStart: " + intent);
    String action = intent.getStringExtra(BluetoothEventReceiver.ACTION);
    Log.d(LOGTAG, BluetoothEventReceiver.ACTION + "=" + action);
    if ("".equals(action)) {
      action = null;
    }

    boolean auto = action == null;

      Log.d(LOGTAG, "Service start or stop manual");
      if (BluetoothEventReceiver.MANUAL_ON.equals(action)) {
        Log.d(LOGTAG, "Manual start");
        startServer();
      } else {
        Log.d(LOGTAG, "Manual stop");
        stopServer();
        stopSelf();
      }
    
  }


  protected void stopServer() {
    if (null != serverThread) {
      Log.d(LOGTAG, "Stopping server");
    } else {
      Log.d(LOGTAG, "Server not runnning");
    }
  }


  protected void startServer() {
    setForeground();
    if (serverThread == null) {
      final Service meService = this;
      Log.d(LOGTAG, "Start receiving thread");
      serverThread = new Thread(new Runnable() {
        public void run() {
          BluetoothSocket btClientSocket = null;
          try {
            // Toast.makeText(meService, "Bluetooth connected", Toast.LENGTH_SHORT).show();
            BufferedInputStream btBufferedIn = new BufferedInputStream(btClientSocket.getInputStream(), 256);
            BufferedOutputStream btBufferedOut = new BufferedOutputStream(btClientSocket.getOutputStream(), 4096);

            // handle 1..n browser-to-pcproxy connections with the one bluetooth conenction
          } catch (Exception e) {
            Log.e(LOGTAG, "Could not handle bluetooth", e);
          } finally {
            meService.stopSelf();
          }
        }
      });
      serverThread.start();
    } else {
      System.out.println("Thread is already running");
    }
  }


  @Override
  public void onDestroy() {
    super.onDestroy();
    Log.d(LOGTAG, "onDestroy");
    if (null != wakeLock) {
      wakeLock.release();
      Log.d(LOGTAG, "Released wake lock");
    }

    if (serverThread != null) {
      serverThread.interrupt();
    }
  }
}